package com.example.module_mine.mine

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.example.lib_common.Router
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.base.BaseViewModel
import com.example.lib_common.event.LoginEvent
import com.example.lib_common.observe.observeEvent
import com.example.lib_log.utils.LoggerUtils
import com.example.lib_storage.AuthMMKV
import com.example.module_mine.R
import com.example.module_mine.adapter.CommonVDBRecyclerAdapter
import com.example.module_mine.databinding.FragmentMineBinding
import com.example.module_mine.databinding.LayoutToolsItemBinding
import com.example.module_mine.viewmodel.MineViewModel


@Route(path = Router.Ui.MineFragment)
class MineFragment : BaseFragment<MineViewModel,FragmentMineBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_mine
    override val mPageCanBack: Boolean = false
    private val mViewModel: MineViewModel by activityViewModels()
    companion object {
        const val CLUB_MGR = "club_mgr"
        const val DVR = "dvr"
        const val GROUP = "group"
        const val MSG_CENTER = "msg_center"
        const val STOLEN = "stolen"
        const val APP_SHARE = "share"
        const val HELP_CENTER = "help_center"
        const val WIKI = "wiki"
        const val CUSTOMER = "customer"
        const val JOIN = "join"
        const val SETTINGS = "settings"

        const val STORE_SEARCH = "store_search"
        const val BOOKING_DRV = "booking_drv"
        const val RESCUE = "rescue"
        const val CARE_SERVICE = "care_service"
        const val FIX_ONLINE = "fix_online"

        const val MALL_ORDER = "store_search"
        const val MALL_FAVORITES = "mall_favorites"
        const val MALL_COUPON = "mall_coupon"
        const val CYCLONE_BEAN = "cyclone_bean"

        const val CHAT = "chat"
        const val ROUTE = "route"


        const val MY_CAR = "my_car"
        const val DRIVING_DATA = "driving_data"
        const val DRIVING_GROUP = "driving_group"
        const val MY_ACTIVITY = "my_activity"
    }
    private val mToolTabItem by lazy {
        arrayListOf(
            TabItem(CLUB_MGR, getString(com.example.lib_common.R.string.string_club_management), R.mipmap.icon_club_management, false),
            TabItem(WIKI, getString(com.example.lib_common.R.string.string_menu_wiki), R.mipmap.icon_menu_wiki, false),
            // TabItem(MSG_CENTER, getString(R.string.string_message_centre), R.mipmap.icon_mine_message_centra, true),
            TabItem(STOLEN, getString(com.example.lib_common.R.string.string_stolen_applications), R.mipmap.icon_stolen_applications, false),
            TabItem(APP_SHARE, getString(com.example.lib_common.R.string.string_app_share), R.mipmap.icon_app_share, false),
            TabItem(HELP_CENTER, getString(com.example.lib_common.R.string.string_help_center), R.mipmap.icon_help, false),
            TabItem(CUSTOMER, getString(com.example.lib_common.R.string.string_contact_customer), R.mipmap.icon_customer, false),
            TabItem(JOIN, getString(com.example.lib_common.R.string.string_commercial_join), R.mipmap.icon_commercial_join, false),
            TabItem(SETTINGS, getString(com.example.lib_common.R.string.string_settings_center), R.mipmap.icon_settings, false),
        )
    }


    private val mServiceTabItem by lazy {
        listOf(
            TabItem(STORE_SEARCH, "寻找门店", R.mipmap.icon_search_store, false),
            TabItem(BOOKING_DRV, "预约试驾", R.mipmap.icon_booking, false),
            TabItem(RESCUE, "一键救援", R.mipmap.icon_rescue, false),
            TabItem(CARE_SERVICE, "保养服务", R.mipmap.icon_care_service, false),
            TabItem(FIX_ONLINE, "在线报修", R.mipmap.icon_fix_online, false),
        )
    }

    private val mMallTabItem by lazy {
        listOf(
            TabItem(MALL_ORDER, "订单", R.mipmap.icon_mall_order, false),
            // TabItem(MALL_FAVORITES, "收藏", R.mipmap.icon_mall_favorites, false),
            TabItem(MALL_COUPON, "优惠券", R.mipmap.icon_mall_coupon, false),
            TabItem(CYCLONE_BEAN, "龙豆兑换", R.mipmap.icon_cyclone_bean, false),
        )
    }

    private val mMyCarTabItem by lazy {
        mutableListOf(
            TabItem(MY_CAR, "添加车辆", R.mipmap.icon_add_motor, false),
            //  TabItem(DRIVING_DATA, "历史骑行", R.mipmap.icon_driving_data, false)
            TabItem(MY_ACTIVITY, "我的活动", R.mipmap.icon_my_activity, false),
            TabItem(DRIVING_GROUP, "骑行组队", R.mipmap.icon_drive_group, false),
        )
    }
    private var mAdapter: CommonVDBRecyclerAdapter<TabItem, LayoutToolsItemBinding>? = null
    //是否需要在OnResume中刷新数据，跳转到其他Activity页面返回需要刷新，增加这个标志位避免重复请求
    private var mNeedRefreshOnResume = false
//    onItemClick: (id: String) -> Unit
    private fun initAdapter() {
        if (mAdapter == null) {
            mAdapter = object : CommonVDBRecyclerAdapter<TabItem, LayoutToolsItemBinding>(R.layout.layout_tools_item, mToolTabItem) {
                override fun convert(holder: BaseDataBindingHolder<LayoutToolsItemBinding>, item: TabItem) {
                    holder.dataBinding?.item = item
//                    holder.dataBinding?.vRedPoint?.visibility = if (item.hasNew) View.VISIBLE else View.GONE
                }
            }
            mBinding.rvTool.adapter = mAdapter
            mAdapter!!.setOnItemClickListener { _, _, position ->
//                onItemClick.invoke(mToolTabItem[position].id)
            }
        } else {
            mAdapter?.setNewInstance(mToolTabItem)
        }
    }
    private val mServiceAdapter by lazy {
        ToolAdapter(mServiceTabItem) {
//            handleServiceTabClick(it.id)
        }
    }

    private val mMallAdapter by lazy {
        ToolAdapter(mMallTabItem) {
//            handleMallTabClick(it.id)
        }
    }
    private val myCarAdapter by lazy {
        ToolAdapter(mMyCarTabItem) {
//            handleMyCarTabClick(it.id)
        }
    }
    override fun initView() {
        LoggerUtils.d("login",AuthMMKV.accessToken)
        initShowView()
        mBinding.rvService.adapter = mServiceAdapter
        mBinding.rvMall.adapter = mMallAdapter
        mBinding.rvMyCar.adapter = myCarAdapter
    }
    override fun onStart() {
        super.onStart()
        //token为空-重置页面
        if (AuthMMKV.accessToken.isEmpty()) {
            onNotLogin()
        }
    }
    private var mInitView = false
    override fun initData() {
        if (AuthMMKV.hasLogin()) {
//            // 获取用户信息
//            mViewModel.getMinePageData()
//            // 获取车辆信息
//            mViewModel.getAllBindMoto()
//            //
//            //mViewModel.getUnreadMessage()
//            // 今日是否已签到
//            mViewModel.pointIsSignIn()
            onLogin()
        } else {
            onNotLogin()
        }
        if (!mInitView) {
            initAdapter()
            mInitView = true
        }
    }

    override fun initListener() {
        mBinding.btnLogin.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.LoginActivity).navigation()
        }
        observeEvent<LoginEvent>(minActiveState = Lifecycle.State.STARTED) {
            LoggerUtils.d("user","${it}")
            onLogin()
            mNeedRefreshOnResume = true
            initData()
        }

//        observeEvent<LogoutEvent>(minActiveState = Lifecycle.State.STARTED) {
////            mViewModel.logout()
//            onNotLogin()
//        }
    }
    private fun onNotLogin() {
        mBinding.lUserInfo.visibility = View.GONE
        mBinding.btnLogin.visibility = View.VISIBLE
//        mBinding.mineModel = null
//        mViewModel.vehicleLiveData.postValue(emptyList())
//        mBinding.lMedals.removeAllViews()
    }

    private fun onLogin() {
        mBinding.btnLogin.visibility = View.GONE
        mBinding.lUserInfo.visibility = View.VISIBLE
    }
    private fun initShowView() {
//        initStatusBar()
        if (AuthMMKV.accessToken.isEmpty()) {
            onNotLogin()
        } else {
            //已经登录
            onLogin()
        }
    }
    data class TabItem(val id: String, var tabName: String, var tabIcon: Int?, var hasNew: Boolean, var tabUrl: String? = null) {

        fun requireIcon(): Any? {
            if (tabUrl != null) return tabUrl
            return tabIcon
        }
    }
    class ToolAdapter(private val mTabItem: List<TabItem>, private val onItemClick: (TabItem) -> Unit) :
        RecyclerView.Adapter<ToolAdapter.ToolViewHolder>() {
        class ToolViewHolder(val binding: LayoutToolsItemBinding) : RecyclerView.ViewHolder(binding.root)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ToolViewHolder {

            val binding =
                DataBindingUtil.inflate<LayoutToolsItemBinding>(LayoutInflater.from(parent.context), R.layout.layout_tools_item, parent, false)
            return ToolViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ToolViewHolder, position: Int) {
            val binding = DataBindingUtil.getBinding<LayoutToolsItemBinding>(holder.itemView)
            binding?.let {
                binding.item = mTabItem[position]
//                binding.vRedPoint.visibility = if (mTabItem[position].hasNew) View.VISIBLE else View.GONE
            }
            holder.binding.lTab.setOnClickListener {
                onItemClick.invoke(mTabItem[position])
            }
        }

        override fun getItemCount(): Int = mTabItem.size
    }
    override fun onResume() {
        super.onResume()
        if (!mNeedRefreshOnResume) {
            mNeedRefreshOnResume = true
            return
        }
        initShowView()
        initData()
    }

}